/**
 * @author ChaP
 * @date 2019/04/14
 * @describe:
 */
package CodingTest.AC20190414;

/**
 * 给定两个数组，编写一个函数来计算它们的交集。

 示例 1:

 输入: nums1 = [1,2,2,1], nums2 = [2,2]
 输出: [2,2]
 示例 2:

 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
 输出: [4,9]
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class intersect {
    public int[] intersect(int[] nums1,int[] nums2){
        HashMap<Integer,Integer> hs1 = new HashMap<Integer,Integer>();
        ArrayList<Integer> list = new ArrayList<>();
        for(int i =0;i<nums1.length;i++){
            if(hs1.containsKey(nums1[i])){
                hs1.put(nums1[i],hs1.get(nums1[i])+1);
            }else{
                hs1.put(nums1[i],1);
            }
        }
        for(int j = 0;j<nums2.length;j++){
            if(hs1.containsKey(nums2[j])){
                if(hs1.get(nums2[j]) == 1){
                    list.add(nums2[j]);
                    hs1.remove(nums2[j]);
                }else{
                    list.add(nums2[j]);
                    hs1.put(nums2[j],hs1.get(nums2[j])-1);
                }
            }
        }
        int result[] = new int [list.size()];
        int i=0;
        for (Integer e:list) {
            result[i++] = e;

        }
        return result;
    }

    public static void main(String[] args) {
        intersect i = new intersect();
        int[] nums1 = {1,2,2,1};
        int[] nums2 = {2,2};
        System.out.println(i.intersect(nums1,nums2));
    }
}
